<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>详情</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="../../layuiadmin/layui/css/layui.css" media="all">
    <style type="text/css">
        /*您可以将下列样式写入自己的样式表中*/
        .childBody {
            padding: 15px;
        }

        /*layui 元素样式改写*/
        .layui-btn-sm {
            line-height: normal;
            font-size: 12.5px;
        }

        .layui-table-view .layui-table-body {
            min-height: 236px;
        }

        /* 改变下拉框和文本框的行高 */
        .layui-table-cell, .layui-input, .layui-unselect, .layui-select {
            height: 30px;
            line-height: 30px;
            bottom: 0;
        }

        /*设置 layui 表格中单元格内容溢出可见样式*/
        .table-overlay .layui-table-view,
        .table-overlay .layui-table-box,
        .table-overlay .layui-table-body {
            overflow: visible;
        }

        .table-overlay .layui-table-cell {
            height: auto;
            overflow: visible;
        }

        /*文本对齐方式*/
        .text-center {
            text-align: center;
        }

        /**
        *遮罩层
         */
        .mask {
            position: fixed;
            top: 0px;
            height: 100%;
            width: 100%;
            filter: alpha(opacity=60);
            background-color: white;
            z-index: 10000000;
            left: 0px;
            opacity: 0.01;
            -moz-opacity: 0.01;
            display: none;
        }
    </style>

</head>
<body>

<div class="layui-form" lay-filter="layuiadmin-app-form-list" id="layuiadmin-app-form-list"
     style="padding: 0px 10px 0 10px;">
    <form class="layui-form" action="" lay-filter="component-form-element">
        <div class="layui-row layui-col-space10">
            <div class="layui-col-lg12" style="float: none">
                <table style="width: 100%;height: 50px;">
                    <tr style="color:#454c51;text-align: center;padding-bottom: 10px;;b-bottom:2px solid darkgray;">
                        <td style="width: 40%;">单据编号:<label id="orderNumber"></label></td>
                        <td style="width: 20%;"><label style="font-size:30px;">房务订单</label></td>
                        <td style="width: 40%;">
                        </td>
                    </tr>
                </table>
            </div>
            <div id="tableRes" class="table-overlay">
                <table id="dataTable" lay-filter="dataTable" class="layui-hide" style="margin-bottom: 0px;">
                </table>
            </div>
        </div>
    </form>
</div>
<div id="mask" class="mask"></div>
<div id="action" class="text-center">
    <button type="button" name="btnSave" class="layui-btn" data-type="save">
        <i class="layui-icon layui-icon-ok-circle"></i>保存
    </button>
    <button type="reset" name="btnReset" class="layui-btn layui-btn-primary" onclick="closeThis()">取消
    </button>
</div>
<div class="layui-form-item layui-hide" id="action1">
    <input type="button" lay-submit lay-filter="entity-submit" name="btnSave" data-type="save" id="entity-submit"
           value="确认添加">
    <input type="button" lay-submit lay-filter="layuiadmin-app-form-edit" id="layuiadmin-app-form-edit"
           value="确认编辑">
</div>
<script src="../../layuiadmin/layui/layui.js"></script>
<script src="../../js/jquery-1.8.3.min.js"></script>
<script>
    /* 基础配置 */
    //订单完成后传递的json信息
    var jsonInfo = "";
    //订单号
    var orderNumber = "";
    //房间信息
    var roomInfo = null;
    //事务信息
    var housekeepInfo = null;

    //向后台获取信息


    /**
     * 关闭该层
     */
    function closeThis() {
        //向后台发送取消占用该订单号
        $.ajax({
            url: '/housekeepOrder/close',
            type: 'get',
            data: {"ordernumber": $("#orderNumber").html()},
            dataType: 'json',
            success: function (data) {
            }
        });
        var index = parent.layer.getFrameIndex(window.name);
        parent.layui.table.reload('dataTable');
        parent.layer.close(index);
    }

    /**
     * 显示遮罩层
     */
    function showMask() {
        $("#mask").css("height", $(document).height());
        $("#mask").css("width", $(document).width());
        $("#mask").show();
    }


    /*
    *隐藏遮罩层
    */
    function hideMask() {
        $("#mask").hide();
    }

    /**
     * 配置本页信息
     * @type {{renderSelectOptions: (function(*, *=): string), typeData: Array, tbData: {number: number, unit: string, supplierId: number, roomId: number, onePrice: number, price: number, cause: string, tempId: number, product_number: number}[]}}
     */
    window.viewObj = {
        tbData: [{
            tempId: new Date().valueOf(),
            roomId: 0,
            housekeep_id: 0,
            idNumber: ''
        }],
        typeData: [],
        renderSelectOptions: function (data, settings) {
            //console.log(data)
            settings = settings || {};
            var valueField = settings.valueField || 'value',
                textField = settings.textField || 'text',
                selectedValue = settings.selectedValue || "";
            var html = [];
            for (var i = 0, item; i < data.length; i++) {
                item = data[i];
                html.push('<option value="');
                html.push(item[valueField]);
                html.push('"');
                if (selectedValue && item[valueField] == selectedValue) {
                    html.push(' selected="selected"');
                }
                html.push('>');
                html.push(item[textField]);
                html.push('</option>');
            }
            return html.join('');
        }
    };
    //下拉框初始化
    $.ajax({
        url: '/housekeepOrder/toAdd',
        type: 'get',
        dataType: 'json',
        async: false,//设置阻断
        data: {"ordernumber": parent.entityType == "toDetails" ? "false" : "true"},
        success: function (data) {
            // console.log(data)
            orderNumber = data.orderNumber;
            roomInfo = data.roomInfo;
            housekeepInfo = data.housekeepInfo;
            //console.log(data);
            $("#orderNumber").html(orderNumber);
        },
        error: function () {
            parent.layer.alert("信息获取失败！");
            return;
        }
    });
    /**
     * 判断本页状态
     */
    if (parent.entityType == "toDetails") {
        $("#action").remove();
        $("#action1").remove();
        $.ajax({
            url: '/housekeepOrder/findDetails',
            type: 'get',
            data: {"id": parent.entityId},
            dataType: 'json',
            async: false,//设置阻断
            success: function (data) {
                $("#orderNumber").html(data.order.ordernumber);
                $("#roomId").find("option[value=" + data.order.roomId + "]").prop("selected", true);
                $("#housekeep_id").find("option[value=" + data.order.housekeep_id + "]").prop("selected", true);
                $("#idNumber").val(data.order.idNumber);
                roomInfo = data.roomInfo;
                viewObj.tbData = data.data;
            },
            error: function () {
                parent.layer.alert("信息获取失败！");
                return;
            }
        });
    }
</script>
<script>
    /** layui配置 */
    layui.config({
        base: '../../layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'form', 'table'], function () {
            var $ = layui.$
                , form = layui.form
                , table = layui.table;

            //数据表格实例化
            var tbWidth = $("#toolbar").width() - 5;
            var layTableId = "layTable";
            var tableIns = table.render({
                elem: '#dataTable',
                id: layTableId,
                data: viewObj.tbData,
                // width: tbWidth,
                cellMinWidth: 60,
                totalRow: true,
                loading: true,
                even: false,
                cols: [[
                    {title: '序号', type: 'numbers', unresize: true},
                    {
                        field: 'roomId',
                        unresize: true,
                        title: '房间名称',
                        templet: function (d) {
                            var options = viewObj.renderSelectOptions(roomInfo, {

                                valueField: "id",
                                textField: "room_name",
                                selectedValue: d.roomId
                            });
                            return '<a lay-event="roomId"></a><select lay-search name="roomId" lay-filter="roomId">' +
                                '<option value="">请选择房间</option>' + options + '</select>';
                        }
                    },
                    {
                        field: 'housekeep_id',
                        unresize: true,
                        title: '房务名称',
                        templet: function (d) {
                            var options = viewObj.renderSelectOptions(housekeepInfo, {
                                valueField: "id",
                                textField: "name",
                                selectedValue: d.housekeep_id
                            });
                            return '<a lay-event="housekeep_id"></a><select lay-search name="housekeep_id" lay-filter="housekeep_id">' +
                                '<option value="">请选择房务</option>' + options + '</select>';
                        }
                    },
                    {field: 'idNumber', title: '备注', edit: 'text', event: 'date'},
                    {
                        field: 'tempId', width: 150, unresize: true, align: 'center', title: '操作', templet: function (d) {
                            return '<a class="layui-btn layui-btn-xs" lay-event="add"><i class="layui-icon layui-icon-add-1"></i></a>'
                                + '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del" lay-id="' + d.tempId + '"><i class="layui-icon layui-icon-delete"></i></a>';
                        }
                    }


                ]],
                done: function (res, curr, count) {
                    // console.log(res.data);
                    viewObj.tbData = res.data;
                    //如果是查询则增加遮罩层
                    if (parent.entityType == "toDetails") {
                        $("[data-field='tempId']").css('display', 'none');
                        showMask();
                    }
                }


            });
            //用于存储事件的类型
            var activeType = "";
            //定义事件集合
            var active = {
                //修改行
                updateRow: function (obj) {
                    var oldData = table.cache[layTableId];
                    // console.log(oldData);
                    for (var i = 0, row; i < oldData.length; i++) {
                        row = oldData[i];
                        if (row.tempId == obj.tempId) {
                            $.extend(oldData[i], obj);
                            return;
                        }
                    }
                    tableIns.reload({
                        data: oldData
                    });
                },
                //删除一项
                removeEmptyTableCache: function () {
                    var oldData = table.cache[layTableId];
                    for (var i = 0, row; i < oldData.length; i++) {
                        row = oldData[i];
                        if (!row || !row.tempId) {
                            oldData.splice(i, 1);
                        }
                        continue;
                    }
                    tableIns.reload({
                        data: oldData
                    });
                },
                //保存
                save: function () {
                    var oldData = table.cache[layTableId];
                    for (var i = 0, row; i < oldData.length; i++) {
                        row = oldData[i];
                        if (!row.roomId) {
                            layer.msg("请检查是否选择完毕！", {icon: 5}); //提示
                            return;
                        }
                    }
                    jsonInfo = {
                        "orderNumber": orderNumber,
                        "housekeep_id": $("#housekeep_id").val(),
                        "roomId": $("#roomId").val(),
                        "idNumber": $("#idNumber").val(),
                        "table": table.cache[layTableId]
                    };
                    // --- 向后台传输数据 --
                    var index = parent.layer.getFrameIndex(window.name);
                    var it = parent.layer.load();
                    $.ajax({
                        url: "/housekeepOrder/add",
                        type: 'post',
                        data: JSON.stringify(jsonInfo),
                        contentType: "application/json;charset=UTF-8",
                        dataType: 'json',
                        async: false,//设置阻断
                        success: function (data) {
                            parent.layer.close(it);//关闭加载窗
                            parent.layer.msg(data.msg, {icon: data.icon, zIndex: layer.zIndex + 100});
                        }
                    });
                    parent.layer.close(it);
                    parent.layer.close(index); //关闭该窗口
                    parent.layui.table.reload('entityTable'); //重载表格
                }
            };
            //激活事件
            var activeByType = function (type, arg) {
                if (arguments.length === 2) {
                    active[type] ? active[type].call(this, arg) : '';
                } else {
                    active[type] ? active[type].call(this) : '';
                }
            };
            //注册按钮事件
            $('.layui-btn[data-type]').on('click', function () {
                var type = $(this).data('type');
                activeByType(type);
            });

            //修改单元格内容
            table.on('edit(dataTable)', function (obj) {
                //获取一行数据
                $.extend(obj.data, {
                    'roomId': obj.data.roomId,
                    'housekeep_id': obj.data.housekeep_id,
                    'idNumber': obj.data.idNumber
                });
                activeByType('updateRow', obj.data);
                tableIns.reload();
            });
            //监听select下拉选中事件
            form.on('select(roomId)', function (data) {
                //得到select原始DOM对象
                var elem = data.elem;
                $(elem).prev("a[lay-event='roomId']").trigger("click");
                tableIns.reload();
            });
            //监听select下拉选中事件
            form.on('select(housekeep_id)', function (data) {
                //得到select原始DOM对象
                var elem = data.elem;
                $(elem).prev("a[lay-event='housekeep_id']").trigger("click");
                tableIns.reload();
            });
            //监听工具条
            table.on('tool(dataTable)', function (obj) {
                var data = obj.data, event = obj.event, tr = obj.tr; //获得当前行 tr 的DOM对象;
                // console.log(data);

                switch (event) {
                    case "add":
                        var oldData = table.cache[layTableId];
                        // console.log(oldData);
                        var newRow = {
                            tempId: new Date().valueOf(),
                            roomId: 0,
                            housekeep_id: 0,
                            idNumber: ''
                        };
                        oldData.push(newRow);
                        tableIns.reload({
                            data: oldData
                        });
                        break;
                    //修改房间下拉框时触发
                    case "roomId":
                        // console.log(data);
                        var select = tr.find("select[name='roomId']");
                        if (select) {
                            var roomId = select.val();
                            var housekeep_id = '';
                            var idNumber = '';
                            if (!roomId) {
                                layer.tips("请选择一个房间", select.next('.layui-form-select'), {tips: [3, '#FF5722']});
                            } else {
                                var oldData = table.cache[layTableId];
                                //如果选中的商品在该单中不存在，则可以添加，已存在则提示并拦截添加。
                                for (var s in oldData) {
                                    if (oldData[s].roomId == roomId && oldData[s].housekeep_id == housekeep_id) {
                                        layer.tips("该房间已存在该事务", select.next('.layui-form-select'), {tips: [3, '#FF5722']});
                                        roomId = "";
                                        housekeep_id = "";
                                        idNumber = ""
                                    }
                                }
                            }
                            $.extend(obj.data, {
                                'roomId': roomId,
                                'idNumber': idNumber
                            });
                            activeType = "roomId";
                            activeByType('updateRow', obj.data);	//更新行记录对象
                        }
                        break;
                    case "housekeep_id":
                        // console.log(data);
                        var select = tr.find("select[name='housekeep_id']");
                        if (select) {
                            var housekeep_id = select.val();
                            var idNumber = '';
                            if (!housekeep_id) {
                                layer.tips("请选择一个事务", select.next('.layui-form-select'), {tips: [3, '#FF5722']});
                            } else {
                                var oldData = table.cache[layTableId];
                                //如果选中的商品在该单中不存在，则可以添加，已存在则提示并拦截添加。
                                for (var s in oldData) {
                                    if (oldData[s].roomId == roomId && oldData[s].housekeep_id == housekeep_id) {
                                        layer.tips("该房间已存在该事务", select.next('.layui-form-select'), {tips: [3, '#FF5722']});
                                        roomId = "";
                                        housekeep_id = "";
                                        idNumber = ""
                                    }
                                }
                            }
                            $.extend(obj.data, {
                                'housekeep_id': housekeep_id,
                                'idNumber': idNumber
                            });
                            activeType = "housekeep_id";
                            activeByType('updateRow', obj.data);	//更新行记录对象
                        }
                        break;
                        点击删除触发的事件
                    case "del":
                        var str = tr.selector.substring(tr.selector.indexOf('="') + 2, tr.selector.indexOf('"]'));
                        if (str == "0") {
                            layer.msg("首条数据不可删除！");
                            break;
                        }
                        layer.confirm('真的删除行么？', function (index) {
                            obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                            layer.close(index);
                            activeByType('removeEmptyTableCache');
                        });
                        break;
                }
            });
        }
    )
</script>
</body>
</html>